﻿using System;
using System.Collections.Generic;
using Clarius.Silverlight.Streaming.Library.Operations;

namespace Clarius.Silverlight.Streaming.Library
{
    public class File
    {
        String name;
        long size;
        String mimeType;
        FileSet parent;

        internal File(String name, long size, String mimeType, FileSet parent)
        {
            this.name = name;
            this.size = size;
            this.mimeType = mimeType;
            this.parent = parent;
        }

        public String Name
        {
            get
            {
                ThrowIfDeleted();
                return name;
            }
        }

        public String MimeType
        {
            get
            {
                ThrowIfDeleted();
                return mimeType;
            }
        }

        public long Size
        {
            get
            {
                ThrowIfDeleted();
                return size;
            }
        }

        internal FileSet Parent
        {
            get
            {
                ThrowIfDeleted();
                return parent;
            }
        }

        public void Download(String localPath)
        {
            ThrowIfDeleted();
            DownloadFileOperation operation = new DownloadFileOperation(this);
            object obj = operation.Execute();

            if (obj is string)
            {
                System.IO.File.WriteAllText(localPath, obj as string);
            }
            else
            {
                System.IO.File.WriteAllBytes(localPath, obj as byte[]);
            }
        }

        // Deletion of files is not yet supported by the Silverlight Streaming server
        //public void Delete()
        //{
        //    DeleteFileOperation operation = new DeleteFileOperation(this);
        //    object obj = operation.Execute();
        //}

        void ThrowIfDeleted()
        {
            if (parent.IsDeleted)
            {
                throw new SilverlightStreamingException(String.Format("File '{0}' belongs to FileSet '{1}' which was previously deleted", name, parent.Name), null);
            }
        }
    }
}
